"""
数据分析
- 以温控单元为组
"""

import os
import pandas as pd
from tensorboardX import SummaryWriter

tensorboard_path = "./board/"
path = "../../Data/furnace86/excel/"
# path = "../../Data/furnace86/excel/minutes/"
rise_file = "20211203-20211207.xlsx"
fall_file = "20211218-20211222.xlsx"

# 温控单元数量
unit_num = 6
# 6路温度数据分别写入到tensorboard
writer = [SummaryWriter(tensorboard_path+"unit"+str(i+1)) for i in range(unit_num)]


def writer_data(w, x, y, s):
    # for i in range(len(w)):
    #     w[i].add_scalar(s, y, x)
    w.add_scalar(s, y, x)


def get_xlsx_data(path='../', file='1.xlsx'):
    filepath = path + file
    df = pd.DataFrame(pd.read_excel(filepath)).fillna(0)  # 空数据补零
    # 读取外围温度和中心温度
    df = df.iloc[:, 1:]
    # df = df.fillna(df.mean())  # 填充
    # 外部温度的均方差
    df_mean = df.iloc[:, 12:18].mean(1)
    df_var = df.iloc[:, 12:18].var(1)
    df.insert(loc=24, column='mean', value=df_mean)
    df.insert(loc=25, column='var', value=df_var)
    # 中心温度的均方差
    df_mean = df.iloc[:, 18:24].mean(1)
    df_var = df.iloc[:, 18:24].var(1)
    df.insert(loc=26, column='in_mean', value=df_mean)
    df.insert(loc=27, column='in_var', value=df_var)
    return df


df_rise = get_xlsx_data(path, rise_file)
df_fall = get_xlsx_data(path, fall_file)
df_rf = pd.concat([df_rise, df_fall], axis=0, ignore_index=True)

# print(df_rf.info())
# print(df_rf.head(5))
# print(df_rf.size)
# print(df_rf.shape)


for i, row in df_rf.iterrows():
    # print(i, row['UNIT1_IR_TEMPLE1'], row['UNIT1_IR_TEMPLE2'])
    for j in range(unit_num):
        writer_data(writer[j], i, row['UNIT1_IR_PID_'+str(j+1)], 'temp_data/pid')
        writer_data(writer[j], i, row['UNIT1_IR_SET_TEMP_'+str(j+1)], 'temp_data/set_temp')
        writer_data(writer[j], i, row['UNIT1_IR_TEMPLE'+str(j+1)], 'temp_data/temp')
        writer_data(writer[j], i, row['UNIT1_IR_TEMPLETC'+str(j+1)], 'temp_data/in_temp')
        writer_data(writer[j], i, row['UNIT1_IR_SET_TEMP_'+str(j+1)]-row['UNIT1_IR_TEMPLE'+str(j+1)], 'diff/set_temp-temp')
        writer_data(writer[j], i, row['UNIT1_IR_TEMPLE'+str(j+1)]-row['UNIT1_IR_TEMPLETC'+str(j+1)], 'diff/temp-in_temp')
        if j == 0:
            writer_data(writer[j], i, row['mean'], 'unit/mean')
            writer_data(writer[j], i, row['var'], 'unit/var')
            writer_data(writer[j], i, row['in_mean'], 'unit/in_mean')
            writer_data(writer[j], i, row['in_var'], 'unit/in_var')
            writer_data(writer[j], i, row['UNIT1_IR_TEMPLECJ1'], 'unit/templecj')
